package current.cas;

import java.util.concurrent.atomic.AtomicInteger;

/*
1、CAS是什么？
CompareAndSet(比较并交换）
 */
public class CASDemo {

    public static void main(String[] args) {

        AtomicInteger atomicInteger = new AtomicInteger(10);

        //true	 current data :2021
        System.out.println(atomicInteger.compareAndSet(10, 2021) + "\t current data :" + atomicInteger.get());

        /*
        再一次修改值
        public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }
        */

        //false	 current data :2021
        System.out.println(atomicInteger.compareAndSet(10, 2020) + "\t current data :" + atomicInteger.get());
        /*
        AtomicInteger.getAndIncrement()是线程安全？i++为什么线程不安全？

         public final int getAndIncrement() {
         //this 当前对象
         //valueOffset 内存偏移量 内存地址
        return unsafe.getAndAddInt(this, valueOffset, 1);

         public final int getAndAddInt(Object var1, long var2, int var4) {
        int var5;
        do {
            var5 = this.getIntVolatile(var1, var2);
        } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

        return var5;
        }
    }
         */
        atomicInteger.getAndIncrement();
    }
}
